package com.ash.test;

import java.io.InputStreamReader;
import java.lang.reflect.Field;
import java.lang.reflect.Method;
import java.util.Map.Entry;
import java.util.Properties;
import java.util.Set;

public class PropertiesUtil {

    private int m;

    public static void main(String[] args) throws Exception {
        loadProperties("my.properties", Constant.class);

        System.out.println(Constant.myStr);
        System.out.println(Constant.xx);
        System.out.println(Constant.myBool);
        System.out.println(Constant.myByte);
        System.out.println(Constant.myChar);
        System.out.println(Constant.myDouble);
        System.out.println(Constant.myFloat);
        System.out.println(Constant.myInteger);
        System.out.println(Constant.myLong);
        System.out.println(Constant.myShort);
    }

    static void testException() {

    }

    static void loadProperties(String propertiesFile, Class<?> clazz) throws Exception {

        InputStreamReader in = new InputStreamReader(PropertiesUtil.class.getResourceAsStream("/" + propertiesFile),
                "UTF-8");

        Properties properties = new Properties();

        properties.load(in);

        Set<Entry<Object, Object>> entrySet = properties.entrySet();

        for (Entry<Object, Object> entry : entrySet) {
            String key = (String) entry.getKey();
            String value = (String) entry.getValue();
            System.out.println(key + ":" + value);

            Field field = Constant.class.getField(key);
            Class<?> fieldType = field.getType();
            if (fieldType == String.class) {
                field.set(null, value);

            } else if (fieldType == Character.class) {
                field.set(null, value.charAt(0));

            } else {
                Method method = fieldType.getMethod("valueOf", entry.getValue().getClass());
                field.set(null, method.invoke(null, value));
            }
        }

    }
}
